<?php

namespace App\Http\Services;
/**
 * Created by PhpStorm.
 * User: thorjiang
 * Date: 2018/5/10
 * Time: 14:40
 */

use App\Models\AdminModel;
use App\Models\BusinessModel;
use App\Models\UserModel;
use App\Models\UserTicketModel;
use App\Models\TicketModel;
use PHPExcel;
use PHPExcel_IOFactory;

/**
 * Class UserTicketDTOBuilderService
 * @package App\Http\Services
 */
class UserTicketDTOBuilderService
{
    /**
     * buildTickets
     * @param $userId
     * @param $userickets
     * @return array
     */
    public static function buildTickets($userId, $userTickets)
    {
        $ret = [];

        foreach ($userTickets as $userTicket) {
            $data = [
                'id' => $userTicket['id'],
                'tax_id' => (string) $userTicket['tax_id'],
                'category_id' => (int) $userTicket['category_id'],
                'bank_name' => (string) $userTicket['bank_name'],
                'bank_code' => (string) $userTicket['bank_code'],
                'email' => (string) $userTicket['email'],
                'name' => (string) $userTicket['name'],
                'title' => (string) $userTicket['title'],
                'money' => (float) $userTicket['money'],
                'title_category' => $userTicket['title_category'],
                'ticket_type' => (int) $userTicket['ticket_type'],
                'address' => (string) $userTicket['address'],
                'mobile' => (string) $userTicket['mobile'],
                'created_at' => $userTicket['created_at'],
            ];

            $ret[] = $data;
        }

        return $ret;
    }

    /**
     * 用来展示所有用户的代金券情况  供admin查询
     * buildTickets
     * @param $userickets
     * @return array
     */
    public static function buildTicketsForBackstage($userTickets)
    {
        $data = [];
        $ids = array_column($userTickets, 'ticket_id');
        $tickets = TicketModel::whereIn('id', $ids)->get()->toArray();
        $ticketsMap = arrToMap($tickets, 'id');
        $ads = [];
        $bus = [];
        $adModels = [];
        $busModelsMap = [];
        foreach ($userTickets as $userTicket) {
            if ($userTicket['operator_type'] == 1) {
                // 商户核销
                $bus[] = $userTicket['operator_id'];
            } elseif ($userTicket['operator_type'] == 2) {
                // 管理员核销
                $ads[] = $userTicket['operator_id'];
            }

            $userIds[] = $userTicket['user_id'];
        }

        $users = UserModel::whereIn('id', $userIds)->get(['id','nickname','avatar','mobile','name'])->toArray();
        $userMap = arrToMap($users, 'id');

        if (!empty($ads)) {
            $adModels = AdminModel::whereIn('id', $ads)->get(['id','username','mobile'])->toArray();
            $adModelsMap = arrToMap($adModels, 'id');
        }

        if (!empty($bus)) {
            $busModels = BusinessModel::whereIn('id', $bus)->get(['id','username','mobile'])->toArray();
            $busModelsMap = arrToMap($busModels, 'id');
        }

        foreach ($userTickets as $userTicket) {
            $userTicket = static::build($userTicket);
            $id = $userTicket['ticket_id'];
            $ticket = isset($ticketsMap[$id]) ? $ticketsMap[$id] : null;
            $userTicket = static::buildTickets2($userTicket, $ticket);
            $user = $userMap[$userTicket['user_id']];
            $userTicket['user'] = $user;

            if ($userTicket['status'] == 1 && $userTicket['operator_type'] == 1) {
                $userTicket['operator'] = $busModelsMap[$userTicket['operator_id']] ?? [];
                $userTicket['operator']['type'] = 1;
                $userTicket['operator']['operator_time'] = $userTicket['updated_at'];
            } elseif ($userTicket['status'] == 1 && $userTicket['operator_type'] == 2) {
                $userTicket['operator'] = $adModelsMap[$userTicket['operator_id']] ?? [];
                $userTicket['operator']['type'] = 2;
                $userTicket['operator']['operator_time'] = $userTicket['updated_at'];
            } else {
                $userTicket['operator'] = new \stdClass();
            }
            $data[] = $userTicket;
        }

        return $data;
    }

    /**
     * @param $userTicket
     * @return mixed
     */
    public static function build($userTicket)
    {
        $userTicket['status'] = (int) $userTicket['status'];

        return $userTicket;
    }

    /**
     * @param $userTicket
     * @return array
     */
    public static function buildForBusiness($userTicket)
    {
        $userTicket['status'] = (int) $userTicket['status'];
        $userTicket['remark'] = (string) $userTicket['remark'];

        $ticketId = $userTicket['ticket_id'];
        $userId = $userTicket['user_id'];
        $user = UserModel::where('id', $userId)->first()->toArray();
        $ticket = TicketModel::where('id', $ticketId)->first();
        $userTicket = static::buildTickets2($userTicket, $ticket);
        $userTicket['user'] = $user;

        return $userTicket;
    }

    /**
     * buildTickets
     * @param $userId
     * @param $userickets
     * @return array
     */
    public static function buildTickets2($userTicket, $ticket = null)
    {
        if (!empty($ticket)) {
            $ticket['code'] = $userTicket['code'];
            $ticket['name'] = (string) $ticket['name'];
            $ticket['payment'] = (string) $ticket['payment'];
            $ticket['bargin_condition'] = (string) $ticket['bargin_condition'];
            unset($ticket['status']);
            $userTicket['ticket'] = $ticket;
        } else {
            $userTicket['ticket'] = new \stdClass();
        }

        return $userTicket;
    }

    public static function export($userMeetings, $filename = '/storage/export.xls')
    {
        $userMeetings = static::buildTickets(0, $userMeetings);
        // excel列  姓名 单位 套餐 联系方式 email 是否核销, 会议名称 , 类型  验证码
        $obj = new PHPExcel();
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('发票导出');

        $obj->getActiveSheet()->setCellValue('A1', '姓名');
        $obj->getActiveSheet()->setCellValue('B1', '联系方式');
        $obj->getActiveSheet()->setCellValue('C1', '纳税号');
        $obj->getActiveSheet()->setCellValue('D1', '公司地址');
        $obj->getActiveSheet()->setCellValue('E1', '邮箱');
        $obj->getActiveSheet()->setCellValue('F1', '抬头');
        $obj->getActiveSheet()->setCellValue('G1', '抬头类型');
        $obj->getActiveSheet()->setCellValue('H1', '报销类型');
        $obj->getActiveSheet()->setCellValue('I1', '金额');
        $obj->getActiveSheet()->setCellValue('J1', '银行');
        $obj->getActiveSheet()->setCellValue('K1', '银行卡号');
        $obj->getActiveSheet()->setCellValue('L1', '创建时间');

        $l = 1;
        $map = [
            'A' => 'name',
            'B' => 'mobile',
            'C' => 'tax_id',
            'D' => 'address',
            'E' => 'email',
            'F' => 'title',
            'G' => 'title_category',
            'H' => 'ticket_type',
            'I' => 'money',
            'J' => 'bank_name',
            'K' => 'bank_code',
            'L' => 'created_at',
        ];
        foreach ($userMeetings as $item) {
            $l++;
            foreach ($map as $k => $v) {
                if ($k == 'A') {
                    $v = empty($item['name']) ? '无' : $item['name'];
                } elseif ($k == 'G') {
                    $v = ($item['title_category'] == 1) ? '公司' : '个人';
                } elseif ($k == 'H') {
                    if ($item['ticket_type'] == 1) {
                        $v = '会务费';
                        //1 会务费 2 会议费 3 住宿费
                    } elseif ($item['ticket_type'] == 2) {
                        $v = '会议费';
                    } else {
                        $v = '住宿费';
                    }
                } elseif ($k == 'L') {
                    $obj->getActiveSheet()->setCellValue($k . $l, $item[$v], true)->setDataType();
                    continue;
                } else {
                    $v = (string) $item[$v];
                }

                $obj->getActiveSheet()->setCellValue($k . $l, $v);
            }
        }

        $objWriter = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
        $objWriter->save('.' . $filename);
        //$objWriter->save('1.xlsx');
        return env('APP_URL') . $filename ;
    }
}
